package com.ymj.netty.client;

import com.ymj.netty.client.handler.BizClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 *  @Description: netty客户端，用于初次netty服务端、客户端通信调试，后续不会用到
 *  @author: yanmj
 *  @Date: 2020-06-07
 */
public class Client {

    public static void main(String[] args) throws InterruptedException, IOException {
        new Client().start();

    }

    private void  start() throws InterruptedException, IOException {
        EventLoopGroup group = new NioEventLoopGroup(1);

        try{
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .remoteAddress(new InetSocketAddress("127.0.0.1",8081))
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Delimiters.lineDelimiter()));
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new IdleStateHandler(60,45,20, TimeUnit.SECONDS));
                            socketChannel.pipeline().addLast(new BizClientHandler());
                            socketChannel.pipeline().addLast(new StringEncoder());

                        }
                    });

            ChannelFuture future = bootstrap.connect().sync();

            //监控控制台输入，发送到服务端
            InputStream in = System.in;

            byte[] buffer = new byte[1024];
            int n = 0;
            while ((n = in.read(buffer)) != -1) {
                future.channel().writeAndFlush(new String(buffer,0,n));
            }


            future.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }

    }
}
